<?php

namespace Portal\MessageBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Portal\MessageBundle\Entity\Message;
use Portal\MessageBundle\Form\MessageType;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Portal\UserBundle\Entity\User;
use Portal\LessonBundle\Entity\Lesson;
use Portal\LessonBundle\Form\LessonType;
use Portal\NotificationBundle\Entity\Notification;
use Portal\MainBundle\Utils\customFunctions;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class MessageController extends Controller
{

  protected $userRole = null;

  public function inboxAction()
  {
    $user = $this->container->get('security.context')->getToken()->getUser();
    // CHECK USER
    if (!is_object($user) || $user == 'anon.') {
      $this->get('session')->setFlash('error', 'Та нэвтэрч орно уу.');
      return $this->redirect($this->generateUrl('homepage'));
    }

    $mailArray = $this->getDoctrine()->getEntityManager()->getRepository('PortalMessageBundle:Message')->inboxList($user->getId(), $user->getRoles(), $this->container->getParameter('inbox'));

    return $this->render('PortalMessageBundle:Inbox:inbox.html.twig', array(
                'mailArray' => $mailArray
            ));
  }

  public function showAction($id)
  {
    // GET USER
    $user = $this->container->get('security.context')->getToken()->getUser();

    // CHECK USER
    if (!is_object($user) || $user == 'anon.') {
      $this->get('session')->setFlash('error', 'Та нэвтэрч орно уу.');
      return $this->redirect($this->generateUrl('homepage'));
    }

    // GET EMAIL INFO
    $mailArray = $this->getDoctrine()->getEntityManager()->getRepository('PortalMessageBundle:Message')->showMessage($id, $user->getRoles(), $user->getId());

    // CHECK EMAIL INFO ISSET
    if (!$mailArray) {
      $this->get('session')->setFlash('error', 'Мессеж байхгүй байна.');
      return $this->redirect($this->generateUrl('homepage'));
    }
    // DO READ
    $this->doReadMessage($id);

    // COLLECT DATA FOR LESSON
    $lessonForm = null;
    $tutorCurrentFee = null;

    if ($this->container->get('security.context')->isGranted('ROLE_TUTOR')) {
      $lession = new Lesson();
      $lessonForm = $this->createForm(new LessonType(), $lession);

      $tutorId = $user->getId();
      $tutorCurrentFee = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorDetail')->getTutorFeeFromTutorDetail($tutorId);
    }

    // RENDER
    return $this->render('PortalMessageBundle:Show:show.html.twig', array(
                'mail' => $mailArray,
                'lessonForm' => $lessonForm->createView(),
                'tutorCurrentFee' => $tutorCurrentFee,
            ));
  }

  public function newAction()
  {
    $entity = new Message();
    $form = $this->createForm(new MessageType(), $entity);

    return $this->render('PortalMessageBundle:New:new.html.twig', array(
                'entity' => $entity,
                'form' => $form->createView(),
            ));
  }

  public function createAction(Request $request)
  {
    $formData = $request->request;

    $formData = $formData->get('portal_messagebundle_messagetype');
    $user = $this->getUserForMessageCreate($formData);

    if ($this->saveMessage($request, $user) == FALSE) {
      $this->get('session')->setFlash('error', 'Алдаа гарлаа илгээж чадсангүй.');
      // HEADER BACK
      return new RedirectResponse($this->getRequest()->headers->get("referer"));
    } else {
      $this->get('session')->setFlash('notice', 'Амжилттай илгээлээ.');
      return $this->redirect($this->generateUrl('homepage'));
    }
  }

  public function outboxAction()
  {
    $user = $this->getUserForMessageCreate();

    $mailArray = $this->getDoctrine()->getEntityManager()->getRepository('PortalMessageBundle:Message')->outboxList($user->getId(), $this->userRole, $this->container->getParameter('outbox'));

    return $this->render('PortalMessageBundle:Outbox:outbox.html.twig', array(
                'mailArray' => $mailArray
            ));
  }

  protected function getUserForMessageCreate($formData = null)
  {
    $user = $this->container->get('security.context')->getToken()->getUser();
    if (!is_object($user)) {

      // Ene email r xereglegch burtgegdsen esexiig shalgaj bn
      $checkUser = $this->findUserEmail($formData['email']);

      if ($checkUser == FALSE) {
        // Ene email r burtgegdeegui bol shireer burtguulex
        $newUser = $this->createNewUserFromMessage($formData);
        $this->loginUser($newUser);

        // SET ROLE          
        $this->userRole = $this->container->getParameter('ROLE_USER');
        // RETURN ROLE
        return $newUser;
      } else {
        // SET ROLE          
        $this->userRole = $this->container->getParameter('ROLE_USER');
        // RETURN ROLE
        return $checkUser;
      }
    }

    $roleArray = $user->getRoles();
    if (!$roleArray) {
      $this->userRole = $this->container->getParameter('ROLE_USER');
    } else {
      $this->userRole = $roleArray[0];
    }

    return $user;
  }

  protected function findUserEmail($email)
  {

    $userObject = $this->getDoctrine()->getEntityManager()->getRepository('PortalMessageBundle:User')->findOneBy(array('email' => $email));

    if ($userObject) {
      return $userObject;
    } else {
      return false;
    }
  }

  protected function createNewUserFromMessage($formData)
  {
    $hashedArray = $this->generatePassword($formData['email']);

    $newUser = new User();
    $newUser->setEmail($formData['email']);
    $newUser->setUsername($formData['email']);
    $newUser->setFirstName($formData['firstName']);
    $newUser->setLastName($formData['lastName']);
    $newUser->setPhone($formData['phone']);
    $newUser->setLocation($formData['location']);
    $newUser->setPassword($hashedArray['hashed']);
    $newUser->setRoles(array($this->container->getParameter('ROLE_USER')));
    $newUser->setCreatedAt(new \DateTime());
    $newUser->setLastIp($_SERVER['REMOTE_ADDR']);
    $newUser->setIsActive($this->container->getParameter('statusActive'));
    $em = $this->getDoctrine()->getManager();
    $em->persist($newUser);
    try {
      $em->flush();
      return $newUser;
    } catch (Exception $e) {
      return false;
    }
    return true;
  }

  protected function generatePassword($email)
  {
    $planPassword = customFunctions::randomRassword($this->container->getParameter('randomPasswordLenght'));
    $hashedPassword = hash('sha512', $planPassword . $email);

    // Save to session to flash plain password
    $session = $this->getRequest()->getSession();
    $session->set('plainPassword', $planPassword);

    return array('planPassword' => $planPassword, 'hashed' => $hashedPassword);
  }

  protected function saveMessage($request, $user)
  {
    $formValues = $request->request->get('portal_messagebundle_messagetype');
    $receiverId = $formValues['receiverId'];
    $receiverRole = $formValues['receiverRole'];

    $entity = new Message();
    $form = $this->createForm(new MessageType($receiverId, $receiverRole), $entity);
    $form->bind($request);
    if ($form->isValid()) {

      $em = $this->getDoctrine()->getManager();
      // SENDER   
      
      $entity->setFirstName($user->getFirstName());
      $entity->setLastName($user->getLastName());
      $entity->setEmail($user->getEmail());
      $entity->setPhone($user->getPhone());
      $entity->setLocationId($user->getLocation());
      $entity->setSentDate(new \DateTime());
      $entity->setSenderId($user->getId());
      $entity->setSenderRole($this->userRole);
      $entity->setStatusSender($this->container->getParameter('messageStatusSent'));
      $entity->setBoxSender($this->container->getParameter('outbox'));

      // RECEIVER
      $entity->setBoxReceiver($this->container->getParameter('inbox'));
      $entity->setStatusReceiver($this->container->getParameter('messageStatusUnread'));
      $entity->setCreatedAt(new \DateTime());
      $entity->setType($this->getDoctrine()->getEntityManager()->getRepository('PortalMessageBundle:MessageType')->find($this->container->getParameter('messageTypeMessage')));

      $em->persist($entity);
      $em->flush();

      
      
      
      
      return true;
    }
    return false;
  }

  protected function loginUser($user)
  {
    $this->container->get('security.context')->setToken(null);
    $token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());
    $this->container->get('security.context')->setToken($token);
  }
  
  

  protected function doReadMessage($id)
  {
    $id = (int) $id;
    $message = $this->getDoctrine()->getEntityManager()->getRepository('PortalMessageBundle:Message')->find($id);

    if ($message) {
      $message->setStatusReceiver($this->container->getParameter('messageStatusRead'));
      $em = $this->getDoctrine()->getManager();
      $em->persist($message);
      $em->flush();
    }
  }
  
//  private function addNotification($messageId)
//  {
//    $user = $this->checkUser();
//
//    $lesson = $this->getDoctrine()->getEntityManager()->getRepository('PortalMessageBundle:Message')->find($messageId);
//
//
//    $notificationType = $this->container->getParameter('notificationRequest');
//    $tableId = $messageId;
//    $toUrl = $this->container->getParameter('notificationUrlRequest') . $messageId;
//    $description = 'Танд тэрнээс хичээл заалгах хүсэлт ирлээ.';
//    $tutorId = $lesson->getTutor()->getId();
//    $userId = $lesson->getUser()->getId();
//    $status = $this->container->getParameter('notificationStatusUnread');
//    $isActive = $this->container->getParameter('statusActive');
//    $createdAt = new \DateTime();
//    // SET DIRECTION
//    if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {
//      $direction = $this->container->getParameter('ROLE_USER');
//      $lastInsertedId = $this->saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, $direction);
//    } else if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {
//      $direction = $this->container->getParameter('ROLE_TUTOR');
//      $lastInsertedId = $this->saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, null, $this->container->getParameter('ROLE_TUTOR'));
//    }
//
//    return $lastInsertedId;
//  }
//
//  /**
//   * Notification хадгалах
//   * 
//   * @param type $noificationType
//   * @param type $tableId
//   * @param type $toUrl
//   * @param type $description
//   * @param type $tutorId
//   * @param type $userId
//   * @param type $status
//   * @param type $isActive
//   * @param type $createdAt
//   */
//  private function saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, $direction = null, $directionTutor = null)
//  {
//    $notification = new Notification();
//    $notification->setNotificationType($notificationType);
//    $notification->setTableId($tableId);
//    $notification->setToUrl($toUrl);
//    $notification->setDescription($description);
//    $notification->setTutorId($tutorId);
//    $notification->setUserId($userId);
//    $notification->setStatus($status);
//    $notification->setIsActive($isActive);
//    $notification->setCreatedAt($createdAt);
//    $notification->setUpdatedAt(new \DateTime());
//
//    if (isset($direction)) {
//      $notification->setUserShowPermission($direction);
//    }
//
//    if (isset($directionTutor)) {
//      $notification->setTutorShowPermission($directionTutor);
//    }
//
//    $em = $this->getDoctrine()->getManager();
//    $em->persist($notification);
//    $em->flush();
//
//    return $notification->getId();
//  }

}